import time
import json
import hashlib
import requests


gl_host = '127.0.0.1'
gl_port = 8080
gl_appid = 1
gl_appkey = 'ab4ea089c20e09e13e596208a0d67b6aafe44ac8ff39621bb13b496d05684886a45ac6c85a22b705eeec2d6f796be1e369628a37fdf83f10842094b3387eed2b'


def md5(src):
    return hashlib.md5(src).hexdigest()


def common_call(method, url, data=None):
    base_url = "/api/v3"
    res_path = base_url + url
    res_url = 'http://%s:%d%s' % (gl_host, gl_port, res_path)
    timestamp = int(time.time())
    args = {
        'timestamp': timestamp,
        'appid': gl_appid
    }
    src = '%s%sappid=%dtimestamp=%d%s' % (method, res_path, gl_appid, timestamp, gl_appkey)
    print(src.lower())
    args['sign'] = md5(src.lower())
    return requests.request(method, res_url, params=args, data=data)


def devices_list():
    url = "/devices"
    rsp = common_call("GET", url)
    return rsp.json()


def add_device():
    url = '/devices'
    args = {
        "imei": "123456789",
        "name": "TEST_DEVICE"
    }
    rsp = common_call("POST", url, data=json.dumps(args))
    return rsp.json()


def remove_device(devid):
    url = "/devices/%d" % devid
    rsp = common_call("DELETE", url)
    return rsp.json()


if __name__ == '__main__':
    dev = add_device()
    print(dev)
    rsp = remove_device(dev["id"]) 
    print(rsp)
    apps = devices_list()
    print(apps)
